<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    width="700px"
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { syncEquipment } from '@/apis/organization/equipment'
import { type Columns, GiForm, type Options } from '@/components/GiForm'
import { useForm } from '@/hooks'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const title = computed(() => ('请选择要同步的类型'))
const formRef = ref<InstanceType<typeof GiForm>>()

const options: Options = {
  form: {
    rules: {
      type: [{ required: true, message: '设备类型不能为空!' }]
    }
  },
  btns: { hide: true }
}

const { form, resetForm } = useForm({
  type: undefined
})

const columns = computed<Columns<typeof form>>(() => [
  {
    label: '设备类型',
    field: 'type',
    type: 'select',
    init: true,
    options: [
      {
        value: 12,
        label: '智慧屏'
      },
      {
        value: 13,
        label: 'IdeaHub'
      },
      {
        value: 14,
        label: 'SmartRooms'
      },
      {
        value: 25,
        label: '第三方会议终端'
      }
    ],
    span: 24
  }
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

const visible = ref(false)
// 新增
const onShow = () => {
  reset()
  visible.value = true
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    syncEquipment(form).then((res) => {
      console.log(res, 'res')
    })
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onShow })
</script>
